const express = require('express');
const userService = require('../service/SysUserService')
const ResultUtil = require('../utils/ResultUtil')

/**
 * 业务控制层： 查询用户列表
 * @param {*} req 
 * @param {*} res 
 */
const userList = async (req, res) => {
  const user = req.query
  let userList = null
  try {
    userList = await userService.selectUserList(user)
    res.send(ResultUtil.success(200, userList))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 根据用户id查询用户信息
 * @param {*} req 
 * @param {*} res 
 */
const selectUserById = async (req, res) => {
  const { id } = req.params
  try {
    const user = await userService.selectUserById(id)
    res.send(ResultUtil.success(200, user))
  } catch (error) {
    res.send(ResultUtil.error(500, error.message))
  }
}

/**
 * 业务控制层： 添加用户
 * @param {*} req 
 * @param {*} res 
 */
const addUser = async (req, res) => {
  const user = req.body
  user.createdAt = new Date()
  console.log(user)
  try {
    await userService.addUser(user)
    res.send(ResultUtil.success(201, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 更新用户
 * @param {*} req 
 * @param {*} res 
 */
const updateUser = async (req, res) => {
  const user = req.body
  user.updatedAt = new Date()
  try {
    await userService.updateUser(user)
    res.send(ResultUtil.success(208, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 删除用户
 * @param {*} req 
 * @param {*} res 
 */
const deleteUser = async (req, res) => {
  const { id } = req.body
  try {
    await userService.deleteUser(id)
    res.send(ResultUtil.success(204, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

module.exports = {
  userList,
  addUser,
  updateUser,
  deleteUser,
  selectUserById
}